﻿using HtmlAgilityPack;
using MDT.LifeSewagePlatform.Conmmon;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

/*********************************************************
 * 命名空间 MDT.LifeSewagePlatform.Extension
 * 接口名称 IpInfoService
 * 开发人员：-nhy
 * 创建时间：2022/4/7 17:41:15
 * 描述说明：
 * 更改历史：
 * 
 * *******************************************************/
namespace MDT.LifeSewagePlatform.Extension
{
    public class IpInfoService
    {
        private IJTokenMappingEntityService jTokenMap;
        private IHttpHelper httpHelper;
        private HtmlDocument document;
        private string[] xPath;

        public IpInfoService()
        {

        }
        public IpInfoService(IJTokenMappingEntityService _jTokenMap, IHttpHelper _httpHelper)
        {
            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
            jTokenMap = _jTokenMap;
            xPath = new[] { "/html/head/script[2]/text()" };///xPath位置
            httpHelper = _httpHelper;
            document = new HtmlDocument();
        }
        public async Task<IpDto> GetIpAddressDtoAsync(string Ip)
        {
            string url = GetUrl(Ip);

            string html = await httpHelper.DownLoadHtmlAsync(url, Encoding.GetEncoding("gb2312"));

            document.LoadHtml(html);
            var script = document.DocumentNode.SelectSingleNode(xPath[0]);
            string[] strs = script.InnerHtml.Split("var");
            var data = strs[2].CutOut("=", ";");


            JToken? jtoken = JsonConvert.DeserializeObject<JToken>(data);
            IpDto? dto = await jTokenMap.GetEntity<IpDto>(jtoken);
            return dto;
        }

        protected string GetUrl(string Params)
        {
            return $"https://www.ip138.com/iplookup.asp?ip={Params}&action=2";
        }
    }
}
